package com.sunfeng.chap2;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.TimeUnit;

/**
 * 验证 write方法具有同步性
 */
public class Test3_3 {

    private static FileOutputStream fileOutputStream;

    private static FileChannel fileChannel;

    public static void main(String[] args) throws IOException, InterruptedException {
        fileOutputStream = new FileOutputStream(new File("d:\\abcd.txt"));
        fileChannel = fileOutputStream.getChannel();

        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread() {
                @Override
                public void run() {

                        try {
                            ByteBuffer buffer1 = ByteBuffer.wrap("oooo1\r\t".getBytes());
                            ByteBuffer buffer2 = ByteBuffer.wrap("oooo2\r\t".getBytes());
                            fileChannel.write(new ByteBuffer[]{buffer1, buffer2});
                        } catch (IOException e) {
                            e.printStackTrace();
                        }


                }
            };
            Thread thread2 = new Thread() {
                @Override
                public void run() {
                        try {
                            ByteBuffer buffer1 = ByteBuffer.wrap("zzzz1\r\t".getBytes());
                            ByteBuffer buffer2 = ByteBuffer.wrap("zzzz2\r\t".getBytes());
                            fileChannel.write(new ByteBuffer[]{buffer1, buffer2});
                        } catch (IOException e) {
                            e.printStackTrace();

                    }
                }
            };
        thread.start();
        thread2.start();
        }



        TimeUnit.SECONDS.sleep(2);
        fileChannel.close();
        fileOutputStream.close();
    }
}
